I know this question at first reads like it's already been addressed on SO multiple times. But I face this issue in spite of all the other questions and answers.
Specifically, I know those 2 things are required (from other answers):
true when it is asyncsendMessage should always be used if it is expected (even just to resolve true)I could not find any other gotchas that would make the following fail:
// content_script.js
const sendMessageToBackground = (payload) =>
new Promise((resolve) => {
chrome.runtime.sendMessage(payload, (response) => {
resolve(response);
});
});
const request = { type: "papersWithCode" };
const backgroundResponse = await sendMessageToBackground(request); // triggers error
console.log(backgroundResponse) // undefined
// background.js
const dummy = async () => {
const html = await fetch("https://stackoverflow.com/");
return 42;
};
chrome.runtime.onMessage.addListener(async (payload, sender, sendResponse) => {
if (payload.type === "papersWithCode") {
const dum = await dummy();
console.log("dum: ", dum); // 42
sendResponse({ success: true, dum });
return true;
}
});
The problem seems to arise from the async nature of dummy() because if I change to the following it all works:
// background.js
const dummy = () => 42
chrome.runtime.onMessage.addListener(async (payload, sender, sendResponse) => {
if (payload.type === "papersWithCode") {
const dum = dummy();
console.log("dum: ", dum); // 42
sendResponse({ success: true, dum });
return true;
}
});